//
//  FImages.swift
//  dypart
//
//  Created by zhuxietong on 2021/3/12.
//

import Foundation
import Eelay

open class FImage: FField,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    public override var defaultProps: [FProps]{
        return [.type(.select),.verify(.reg("\\S+"))]
    }
    public let selectBt = ASButtonNode()
    

    open var hasSrc:Bool{
        if let _ = value as? UIImage{
           
            return true
        }
        if let src = value as? String{
            return src.len > 1
        }
        return false
    }
    var image:UIImage? = nil{
        didSet{
            imgN.image = image
        }
    }
    public let imgN = JoImageNode()
    public let nameL = ASTextNode2()
    public let holderV = ASImageNode()
    public let holderL = ASTextNode2()
    
    
    open override func willLayoutRules() {
        super.willLayoutRules()
        selectBt.addTarget(self, action: #selector(chooseImg), forControlEvents: .touchUpInside)

    }
    open override func addLayoutRules() {
        imgN.backgroundColor = UIColor.color(light: "#8882", dark: "#8882")
        imgN.bsui.set(radius: 2, width: nil, color: nil)
        imgN.ui.holder(type: .grayBack)
        holderL.attributedText = _lable
    }
    open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    }
    
    
    @objc open func chooseImg()
    {
        mo.controller?.view.endEditing(true)

        weak var wself = self
        JoAlertView(info: "提示".loc,"选择图片".loc,"取消".loc).append(title: "拍照".loc, action: {wself?.selectImage(index: 0)}).append(title: "图库选择".loc, action: {wself?.selectImage(index: 1)}).sheet.show(at: mo.controller)
        
    }
    
    open override func mo_model_reload() {
        
    }
    
    open override func updateDispaly() {
        
        if let img = value as? UIImage{
            imgN.image = img
            return
        }
        if let src = value as? String{
            imgN.img_url = src
            return
        }
        imgN.img_url = ""
        setNeedsLayout()
        layoutIfNeeded()
    }
    
    
    
    open func selectImage(index:NSInteger)
    {
        let picker:UIImagePickerController = UIImagePickerController()
        picker.delegate = self
        if index == 1
        {
            picker.sourceType = UIImagePickerController.SourceType.photoLibrary
        }
        else
        {
            picker.sourceType = UIImagePickerController.SourceType.camera
        }
        picker.allowsEditing = true
        mo.controller?.present(picker, animated: true) { () -> Void in
        }
    }
    
    
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
     
        if let image = info[.originalImage] as? UIImage{
            let smallPng = image.commpress(maxSize: 800)
            self.updateImg(img: smallPng)
            picker.dismiss(animated: true) { () -> Void in

            }
        }
    }
    
//
//    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//
//    }
//
    public func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

        let smallPng = image.commpress(maxSize: 800)
        self.updateImg(img: smallPng)
        picker.dismiss(animated: true) { () -> Void in

        }

    }
    
    open func updateImg(img:UIImage)
    {

//        HUD.share.mode(.indeterminate).show()
//        QNOss.share.upload(img) { (status) in
//            print("___KKKK",status)
//            HUD.share.hide(animated: false)
//            switch status {
//            case .failed(msg: let msg):
//                msg.alert()
//            case .success(url: let url, key: _, info: _):
//                self.update(value: url, edit: .select)
//                break
//            }
//
//        }
        

//
//        JoTask().log.log_response().url(mo.model[FK.Img.upload,""]).params(["name":"ios"]).append(file: file).json_handle { (status, message, obj, response) in
//            HUD.share.hide(animated: false)
//            if status.isSuccess{
//                if let dict = obj as? NSMutableDictionary
//                {
//                    wself?.imgN.image = img
//                    wself?.update(value: dict["v",""], edit: .select)
//                    wself?.succeedUploadImg()
//                }
//                "图片上传成功".loc.alert()
//                return
//            }
//            else
//            {
//                "图片上传失败".loc.alert()
//            }
//        }.upload()
    }
    
    open func succeedUploadImg()
    {
//        self.delegate?.touch(cell:self, actionID: "succeed_upload_img", model: self.model)
    }
    

    
    
    public func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
    {
        
        picker.dismiss(animated: true) { () -> Void in
        }
    }
    
    
    
}

